from forms.ui_config_server import Ui_Dialog
from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSignal
import paramiko

class DialogConfigServer(QtWidgets.QDialog, Ui_Dialog):
    signal_config_server = pyqtSignal(str, str, str, str, str)  # 发送配置的服务器信息

    def __init__(self, parent=None,host='',port='',user='',password='',directory=''):
        super(DialogConfigServer, self).__init__(parent)
        self.setupUi(self)

        # 设置初始值
        self.LineEdit.setText(host)
        self.LineEdit_2.setText(port)
        self.LineEdit_3.setText(user)
        self.LineEdit_4.setText(password)
        self.LineEdit_5.setText(directory)

        # 将默认的ok与cancel文本修改为确定与取消
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText('确定')
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setText('取消')

        # 连接信号槽
        self.pushButton.clicked.connect(self.test_connect)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def test_connect(self): 
        # 测试连接数据库
        self.host = self.LineEdit.text()
        self.port = self.LineEdit_2.text()
        self.user = self.LineEdit_3.text()
        self.password = self.LineEdit_4.text()
        self.directory = self.LineEdit_5.text()
        try:
            # ssh连接远程服务器，并检测目录是否存在
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(self.host, self.port, self.user, self.password)
            stdin, stdout, stderr = ssh.exec_command('test -d ' + self.directory)
            result = stdout.read().decode()
            if stdout.channel.recv_exit_status() == 0:
                self.label_6.setText('配置正常！')
                self.label_6.setStyleSheet('color: green')
                return
        except:
            self.label_6.setText('配置错误！')
            self.label_6.setStyleSheet('color: red')

    def accept(self):
        # 配置数据库
        self.host = self.LineEdit.text()
        self.port = self.LineEdit_2.text()
        self.user = self.LineEdit_3.text()
        self.password = self.LineEdit_4.text()
        self.directory = self.LineEdit_5.text()
        if self.host == '' or self.port == '' or self.user == '' or self.password == '' or self.directory == '':
            self.label_6.setText('配置不能为空！')
            self.label_6.setStyleSheet('color: red')
        else:
            self.signal_config_server.emit(self.host, self.port, self.user, self.password, self.directory)
            super(DialogConfigServer, self).accept()